import sys
from PySide6.QtCore import Qt
from mysql import MyMysql
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from PySide6.QtGui import QIcon, QPainter
from PySide6.QtWidgets import *
from connect import User, Device, Order
from PySide6.QtWidgets import QMessageBox
from PySide6.QtCharts import QChart, QLineSeries, QChartView, QValueAxis, QPieSeries


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.mysql = MyMysql()
        self.resize(1200, 800)
        self.setWindowIcon(QIcon('cartoon3.ico'))
        # 连接数据库
        uname = "root"
        pwd = "123456"
        host = "127.0.0.1"
        port = "3306"
        db = "798"
        self.engine = create_engine(f"mysql+pymysql://{uname}:{pwd}@{host}:{port}/{db}")
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
        self.is_hidden = False

        # 顶部导航栏主题
        label_title = QLabel('后台管理系统')
        label_title.setStyleSheet('font-size:17px;color: #ce642e;margin-left:400px')
        bt1 = QPushButton("")
        icon1 = QIcon("菜单.png")
        bt1.setIcon(icon1)
        bt1.setStyleSheet('color: white;')
        bt1.mousePressEvent = lambda event: self.toggle()
        # 顶部导航栏  左右布局（左：title，右：收缩）
        layout_top = QHBoxLayout()
        layout_top.setAlignment(Qt.AlignmentFlag.AlignLeft)
        layout_top.addWidget(bt1)
        layout_top.addWidget(label_title)

        # 左侧栏按钮
        bt_menu = QPushButton("统计")
        icon_menu = QIcon("0-订单管理.png")
        bt_menu.setIcon(icon_menu)
        bt_menu.setStyleSheet(
            "background-color: rgb(255,255,255);color:black; width: 80px; height: 50px; font-size: 14px;border:1px solid black")

        bt2 = QPushButton("客户管理")
        icon2 = QIcon("用户.png")
        bt2.setIcon(icon2)
        bt2.setStyleSheet("background-color: rgb(255,255,255);color:black;width: 80px;height: 50px;font-size: 14px;border:1px solid black")
        bt3 = QPushButton("设备管理")
        icon3 = QIcon("设备管理用户管理.png")
        bt3.setIcon(icon3)
        bt3.setStyleSheet("background-color: rgb(255,255,255);color:black;width: 80px;height: 50px;font-size: 14px;border:1px solid black")
        bt4 = QPushButton("订单管理")
        icon4 = QIcon("0-订单管理.png")
        bt4.setIcon(icon4)
        bt4.setStyleSheet("background-color: rgb(255,255,255);color:black;width: 80px;height: 50px;font-size: 14px;border:1px solid black")

        # bt_menu.mousePressEvent = lambda event: self.show_new()
        bt_menu.mousePressEvent = lambda event: self.show_charts()
        bt2.mousePressEvent = lambda event: self.users_info()
        # bt2.mousePressEvent = lambda event: self.show_line()
        bt3.mousePressEvent = lambda event: self.equip_info()
        bt4.mousePressEvent = lambda event: self.order_info()
        # 左侧栏布局
        layout_left = QVBoxLayout()
        layout_left.setAlignment(Qt.AlignmentFlag.AlignTop)
        layout_left.setSpacing(40)

        layout_left.addWidget(bt_menu)
        layout_left.addWidget(bt2)
        layout_left.addWidget(bt3)
        layout_left.addWidget(bt4)

        self.window_left = QWidget(self)
        self.window_left.setFixedSize(100, 600)
        self.window_left.setStyleSheet("background-color: rgb(19,30,70);color: #b7bac2;")
        self.window_left.setLayout(layout_left)
        # 内容区域
        self.stacked_widget = QStackedWidget()
        self.stacked_widget.setStyleSheet("background-color: rgb(46,56,96);color: white;")

        # 左右布局（左：左侧栏，右：内容区）
        layout_center = QHBoxLayout()
        layout_center.setContentsMargins(0, 0, 0, 0)
        layout_center.addWidget(self.window_left)
        layout_center.addWidget(self.stacked_widget)
        window_center = QWidget(self)
        window_center.setLayout(layout_center)

        window_top = QWidget()
        window_top.setStyleSheet("background-color: #1b233b;")
        window_top.setLayout(layout_top)

        # 上下布局（上：标题区，下：功能和内容区）
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(window_top)
        layout.addWidget(window_center)
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
        # self.users_info()
        self.show_charts()
        # self.show_new()

    # 赋能：点击事件
    def mousePressEvent(self, event):
        pass

    # 左侧栏（显示/消失）
    def toggle(self):
        print(self.window_left.isVisible())
        if self.window_left.isVisible():
            # self.is_hidden = True
            self.window_left.show()
            self.window_left.setVisible(False)
        else:
            # self.window_left.setMinimumWidth(100)
            self.window_left.show()
            self.window_left.setVisible(True)

    def show_charts(self):
        """显示订单月度收入折线图,饼状图默认5月"""
        month = self.mysql.select_month()
        # print(month)
        m_incomes = self.mysql.select_month_income()
        # print(m_incomes)

        # 创建折线图
        chart1 = QChart()
        chart1.setTitle("月度收入情况")
        chart1.legend().hide()
        chart1.setAnimationOptions(QChart.AnimationOption.AllAnimations)

        # 添加数据系列
        series = QLineSeries()
        for i, value in enumerate(m_incomes):
            series.append(i + 5, value)  # 月份从5开始
        chart1.addSeries(series)
        # 设置x坐标轴
        axis_x = QValueAxis()
        axis_x.setTitleText("月份")
        axis_x.setRange(5, 10)  # 月份范围从5到10
        chart1.addAxis(axis_x, Qt.AlignmentFlag.AlignBottom)
        chart1.axisX().setTickCount(6)  # 设置横坐标刻度数量
        series.attachAxis(axis_x)
        # 设置y坐标轴
        axis_y = QValueAxis()
        axis_y.setTitleText("收入(元)")
        axis_y.setRange(0, max(m_incomes))
        chart1.addAxis(axis_y, Qt.AlignmentFlag.AlignLeft)
        series.attachAxis(axis_y)
        # 显示图表
        chart_view = QChartView(chart1)
        chart_view.setRenderHint(QPainter.RenderHint.Antialiasing)

        # 创建垂直布局并添加折线图
        v_layout = QVBoxLayout()
        v_layout.addWidget(chart_view)
        v_layout.setAlignment(chart_view, Qt.AlignmentFlag.AlignTop)  # 设置折线图顶端对齐

        """设备收入情况"""
        # 创建设备占比饼图
        self.pie_series1 = QPieSeries()
        rest = self.mysql.month_equip_incomes(5)
        print(rest)
        total = sum(num for _, num in rest)
        print(total)
        for index, value in list(rest):
            percent = value / total * 100
            percent = round(percent, 1)
            print(percent)
            self.pie_series1.append(f'{index}{percent}%', value)

        pie_chart1 = QChart()
        pie_chart1.addSeries(self.pie_series1)
        pie_chart1.setTitle("设备的占比图")
        # # 设置百分比显示格式
        self.pie_series1.setLabelsVisible(True)
        pie_chart1.legend().setAlignment(Qt.AlignmentFlag.AlignBottom)

        # 创建图表视图并添加到窗口
        chart_view2 = QChartView(pie_chart1)
        chart_view2.setRenderHint(QPainter.RenderHint.Antialiasing)

        """区域收入情况"""
        # 创建区域占比饼图
        self.pie_series2 = QPieSeries()
        rest = self.mysql.location_query(5)
        print(rest)
        total = sum(num for _, num in rest)
        print(total)
        for index, value in list(rest):
            percent = value / total * 100
            percent = round(percent, 1)
            print(percent)
            self.pie_series2.append(f'{index}{percent}%', value)

        pie_chart2 = QChart()
        pie_chart2.addSeries(self.pie_series2)
        pie_chart2.setTitle("区域收入占比图")

        self.pie_series2.setLabelsVisible(True)
        pie_chart2.legend().setAlignment(Qt.AlignmentFlag.AlignBottom)
        chart_view3 = QChartView(pie_chart2)
        chart_view3.setRenderHint(QPainter.RenderHint.Antialiasing)

        # 创建垂直布局并添加折线图
        v_layout = QVBoxLayout()
        v_layout.addWidget(chart_view)

        # 创建水平布局并添加两个饼图
        hbox = QHBoxLayout()
        button_layout = QVBoxLayout()
        hbox.addLayout(button_layout)
        hbox.addWidget(chart_view2)
        hbox.addWidget(chart_view3)

        but5 = QPushButton("5")
        but6 = QPushButton("6")
        but7 = QPushButton("7")
        but8 = QPushButton("8")
        but9 = QPushButton("9")
        but10 = QPushButton("10")
        but5.clicked.connect(lambda: self.update_data(5))
        but6.clicked.connect(lambda: self.update_data(6))
        but7.clicked.connect(lambda: self.update_data(7))
        but8.clicked.connect(lambda: self.update_data(8))
        but9.clicked.connect(lambda: self.update_data(9))
        but10.clicked.connect(lambda: self.update_data(10))
        button_layout.addWidget(but5)
        button_layout.addWidget(but6)
        button_layout.addWidget(but7)
        button_layout.addWidget(but8)
        button_layout.addWidget(but9)
        button_layout.addWidget(but10)

        # 创建一个容器部件并将布局添加到其中
        page = QWidget()
        page.setLayout(v_layout)
        page.layout().addLayout(hbox)

        # 设置主窗口的中心部件为容器部件
        self.stacked_widget.addWidget(page)
        self.stacked_widget.setCurrentIndex(0)

    def show_data(self, num):
        """设备占比"""
        rest = self.mysql.month_equip_incomes(num)
        print(rest)
        total = sum(num for _, num in rest)
        print(total)
        for index, value in list(rest):
            percent = value / total * 100
            percent = round(percent, 1)
            print(percent)
            self.pie_series1.append(f'{index}{percent}%', value)
        self.pie_series1.setLabelsVisible(True)

        """区域占比"""
        rest = self.mysql.location_query(num)
        print(rest)
        total = sum(num for _, num in rest)
        print(total)
        for index, value in list(rest):
            percent = value / total * 100
            percent = round(percent, 1)
            print(percent)
            self.pie_series2.append(f'{index}{percent}%', value)
        self.pie_series2.setLabelsVisible(True)

    def update_data(self, new_num):
        print(new_num)
        self.pie_series1.clear()
        self.pie_series2.clear()
        self.show_data(new_num)

    def users_info(self):
        """用户信息显示"""
        self.tab_users = QTableWidget()
        self.tab_users.setStyleSheet("color:black;background-color:white")
        if self.stacked_widget.count() == 1:
            self.tab_users.setColumnCount(11)

        self.tab_users.setColumnCount(11)
        self.tab_users.setHorizontalHeaderLabels(["id", "姓名", "密码", "手机号", "是否是管理员", "注册时间", "卡号", "积分", "最后登录时间", "是否删除"])
        self.load_user()

        layout_tab_user = QVBoxLayout()
        layout_tab_user.addWidget(self.tab_users)

        user_page = QWidget()
        user_page.setLayout(layout_tab_user)
        self.stacked_widget.addWidget(user_page)
        self.stacked_widget.setCurrentIndex(1)

    def load_user(self):
        # users = self.session.query(User).filter(User.is_admin == 0).all()
        users = self.mysql.select_all_user()
        # print(users)
        self.tab_users.setRowCount(len(users))
        for index, user in enumerate(users):
            # print("index", index)
            # for col, data in enumerate(
            #         [user.u_id, user.name, user.password, user.phone, user.is_admin, user.register_date,
            #          user.card_number, user.points, user.last_login_date]):
            for col, data in enumerate(user):
                self.tab_users.setItem(index, col, QTableWidgetItem(str(data)))

            delete_button_user = QPushButton("删除用户")
            delete_button_user.clicked.connect(lambda checked, row=index: self.delete_user(row))
            delete_button_user.setStyleSheet("background-color:green")
            self.tab_users.setCellWidget(index, 9, delete_button_user)

            self.open_button_user = QPushButton("开卡")
            self.open_button_user.clicked.connect(lambda: self.open_user(index))
            self.open_button_user.setStyleSheet("background-color:green")
            self.tab_users.setCellWidget(index, 10, self.open_button_user)

    def delete_user(self, row):
        user_id = self.tab_users.item(row, 0).text()
        print(row, user_id)
        result = QMessageBox.question(self, "对话框", "确定要删除吗？", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if result == QMessageBox.StandardButton.Yes:
            print("确定")
            QMessageBox.information(self, "提示", "已删除该用户")
            self.mysql.delete_user(user_id)
            self.load_user()
        else:
            QMessageBox.information(self, "提示", "已取消此操作")
            print("取消")

    def open_user(self, row):
        print("开卡")

    # 设备内容
    def equip_info(self):
        self.tab_equip = QTableWidget()
        self.tab_equip.setStyleSheet("color:black;background-color:white")
        if self.stacked_widget.count() == 2:
            self.tab_equip.setColumnCount(6)
        self.tab_equip.setHorizontalHeaderLabels(["设备id", "设备名称", "安装位置", "二维码", "是否正常使用", "状态"])
        self.load_equip()

        layout_tab_equip = QVBoxLayout()
        layout_tab_equip.addWidget(self.tab_equip)

        equip_page = QWidget()
        equip_page.setLayout(layout_tab_equip)
        self.stacked_widget.addWidget(equip_page)
        self.stacked_widget.setCurrentIndex(2)

    def load_equip(self):
        # devices = self.session.query(Device).all()
        devices = self.mysql.select_all_device()
        self.tab_equip.setRowCount(len(devices))
        for index, device in enumerate(devices):
            # for col, data in enumerate([device.d_id, device.category_name, device.install_location, device.qr_code,
            #                             device.is_functional]):
            for col, data in enumerate(device):
                self.tab_equip.setItem(index, col, QTableWidgetItem(str(data)))
            delete_button_equip = QPushButton("删除设备")
            delete_button_equip.clicked.connect(lambda checked,row=index: self.delete_equip(row))
            delete_button_equip.setStyleSheet("background-color:green")
            self.tab_equip.setCellWidget(index, 5, delete_button_equip)


    def delete_equip(self,row):
        d_id = self.tab_equip.item(row, 0).text()
        print(row, d_id)
        result = QMessageBox.question(self, "对话框", "确定要删除吗？", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if result == QMessageBox.StandardButton.Yes:
            print("确定")
            QMessageBox.information(self, "提示", "已删除该设备")
            self.mysql.delete_equip(d_id)
            self.load_equip()
        else:
            QMessageBox.information(self, "提示", "已取消此操作")
            print("取消")

    def order_info(self):
        self.tab_order = QTableWidget()
        self.tab_order.setStyleSheet("color:black;background-color:white")
        if self.stacked_widget.count() == 3:
            self.tab_order.setColumnCount(7)
        self.load_orders()
        layout_tab_order = QVBoxLayout()
        layout_tab_order.addWidget(self.tab_order)

        order_page = QWidget()
        order_page.setLayout(layout_tab_order)
        self.stacked_widget.addWidget(order_page)
        self.stacked_widget.setCurrentIndex(3)

    def load_orders(self):
        # orders = self.session.query(Order).all()
        orders = self.mysql.select_all_order()
        # print(">>>>>", orders)
        self.tab_order.setRowCount(len(orders))
        self.tab_order.setHorizontalHeaderLabels(["订单id", "用户id", "设备id", "消费时间", "消费金额", "支付方式", "状态"])
        for index, order in enumerate(orders):
            # for column, value in enumerate(
            #         [order.order_id, order.user_id, order.device_id, order.consume_time, order.consume_amount,
            #          order.payment_method]):
            for col, data in enumerate(order):
                self.tab_order.setItem(index, col, QTableWidgetItem(str(data)))
            delete_button_order = QPushButton("删除订单")
            delete_button_order.clicked.connect(lambda checked, row=index: self.delete_order(row))
            delete_button_order.setStyleSheet("background-color:green")
            self.tab_order.setCellWidget(index, 6, delete_button_order)

    def delete_order(self, row):
        o_id = self.tab_order.item(row, 0).text()
        print(row, o_id)
        result = QMessageBox.question(self, "对话框", "确定要删除吗？", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if result == QMessageBox.StandardButton.Yes:
            print("确定")
            QMessageBox.information(self, "提示", "已删除该订单")
            self.mysql.delete_order(o_id)
            self.load_orders()
        else:
            QMessageBox.information(self, "提示", "已取消此操作")
            print("取消")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
